package com.xz.knowledgeDuplication.thread.advice;

/**
 * 生产者/消费者 信号灯法
 * @author 召
 * @date 2022-07-27 21:49:08
 */
public class Flag {

    public static void main(String[] args) {
        TV tv = new TV();
        new Thread(new Player(tv)).start();
        new Thread(new Watcher(tv)).start();
    }
}

class Player implements Runnable {

    private TV tv;

    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i % 3 != 0) {
                tv.play("快乐大本营");
            } else {
                tv.play("抖音记录美好生活");
            }
        }
    }
}

class Watcher implements Runnable {

    private TV tv;

    public Watcher(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}

class TV {
    /**
     * 表演的节目
     */
    private String voice;

    /**
     * 标志位 false: 未表演 true: 已表演
     */
    private boolean flag = false;

    public synchronized void play(String voice) {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了: " + voice);
        this.voice = voice;
        this.flag = !this.flag;
        this.notifyAll();
    }

    public synchronized void watch() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众观看了: " + this.voice);
        this.flag = !this.flag;
        this.notifyAll();
    }
}